package com.ch.d0304;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@WebListener
public class OnlineListener implements ServletContextListener, HttpSessionListener, HttpSessionAttributeListener {

    public static Map<String, Date> onlineUsers = new HashMap<>();
    public OnlineListener() {
    }

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        /* This method is called when the servlet context is initialized(when the Web application is deployed). */
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        /* This method is called when the servlet Context is undeployed or Application Server shuts down. */
    }

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        /* Session is created. */
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        /* Session is destroyed. */
    }

    @Override
    public void attributeAdded(HttpSessionBindingEvent sbe) {
        /* This method is called when an attribute is added to a session. */
        sbe.getName();// 添加到会话中的属性名  => loginedUser
        sbe.getValue();// 添加到会话中的属性值
        if(sbe.getName().equals("loginedUser")){
            onlineUsers.put((String) sbe.getValue(),
                    (Date) sbe.getSession().getAttribute("loginedTime"));
        }
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent sbe) {
        /* This method is called when an attribute is removed from a session. */
        if(sbe.getName().equals("loginedUser")){
            onlineUsers.remove((String) sbe.getValue());
        }
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent sbe) {
        /* This method is called when an attribute is replaced in a session. */
        if(sbe.getName().equals("loginedUser")){
            String oldName = (String) sbe.getValue();
            String newName = (String) sbe.getSession().getAttribute("loginedUser");
//            String loginedUser = (String) sbe.getSession().getAttribute("loginedUser");
            //移除原来的名字
            onlineUsers.remove(oldName);
            // 添加新的名字
            onlineUsers.put(newName,
                    (Date) sbe.getSession().getAttribute("loginedTime"));
        }
    }
}
